import org.json.JSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/update_book")
public class UpdateBook extends HttpServlet {
    private static final long serialVersionUID = 1L;

   
    private static final String URL = "jdbc:mysql://localhost:3306/linux_exam";
    private static final String USER = "root";
    private static final String PASSWORD = "1qaz@WSX#EDC";

   
    public JSONObject updateBook(String bookNumber, String bookName, String bookAuthor) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
           
             Class.forName("com.mysql.cj.jdbc.Driver");
            
            connection = DriverManager.getConnection(URL, USER, PASSWORD);

          
            String sqlUpdate = "UPDATE t_book SET name =?, author =? WHERE number =?";
            preparedStatement = connection.prepareStatement(sqlUpdate);
            preparedStatement.setString(1, bookName);
            preparedStatement.setString(2, bookAuthor);
            preparedStatement.setString(3, bookNumber);

            
             int rowsAffected = preparedStatement.executeUpdate();
            if (rowsAffected > 0) {
                
                String sqlSelect = "SELECT * FROM t_book WHERE number =? AND name =? AND author =?";
                preparedStatement = connection.prepareStatement(sqlSelect);
                preparedStatement.setString(1, bookNumber);
                preparedStatement.setString(2, bookName);
                preparedStatement.setString(3, bookAuthor);
                resultSet = preparedStatement.executeQuery();
                if (resultSet.next()) {
                    JSONObject updatedBook = new JSONObject();
                    updatedBook.put("number", resultSet.getString("number"));
                    updatedBook.put("name", resultSet.getString("name"));
                    updatedBook.put("author", resultSet.getString("author"));
                     return updatedBook;
                }else {
               
                System.err.println("更新图书成功，但查询更新后记录失败，可能存在数据不一致问题");
                return null;
            }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
           
              try {
                if (resultSet!= null) {
                    resultSet.close();
                }
                if (preparedStatement!= null) {
                    preparedStatement.close();
                }
                if (connection!= null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
         response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        
         String bookNumber = request.getParameter("number");
        String bookName = request.getParameter("name");
        String bookAuthor = request.getParameter("author");

        
         if (bookNumber == null || bookNumber.isEmpty() || bookName == null || bookName.isEmpty() || bookAuthor == null || bookAuthor.isEmpty()) {
            JSONObject errorJson = new JSONObject();
            errorJson.put("error", "图书编号、名称和作者不能为空");
            out.println(errorJson.toString());
            out.close();
            return;
        }

        JSONObject resultJson = updateBook(bookNumber, bookName, bookAuthor);
        if (resultJson!= null) {
                response.getWriter().println(resultJson.toString());
        } else {
            JSONObject errorJson = new JSONObject();
            errorJson.put("error", "图书更新失败");
            response.getWriter().println(errorJson.toString());
            }


            out.close();
     }
}

